package com.systemsjr.mpf.expense;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;

import com.systemsjr.mpf.IntentHandler;
import com.systemsjr.mpf.R;
import com.systemsjr.mpf.account.Account;
import com.systemsjr.mpf.account.AccountInstance;
import com.systemsjr.mpf.account.AccountInstanceList;
import com.systemsjr.mpf.account.ManageAccountInstanceActivity;
import com.systemsjr.mpf.db.ExpenseTypeContentProvider;

public class ManageExpenseActivity extends Activity {

	private Cursor c;
	private final HashMap<String, AccountInstance> instancesMap = new HashMap<String, AccountInstance>();
	private final HashMap<String, ExpenseType> typesMap = new HashMap<String, ExpenseType>();

	public static final String[] PROJECTIONS = { Expense.ID,
			Expense.DESCRIPTION, Expense.EXPENSE_TYPE,
			Expense.ACCOUNT_INSTANCE, Expense.AMOUNT };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_manage_expense);
		final Expense expense = new Expense();

		final SimpleDateFormat sdf = new SimpleDateFormat(Expense.DATE_FORMAT);

		final AutoCompleteTextView typeText = (AutoCompleteTextView) findViewById(R.id.type_of_expense);
		final AutoCompleteTextView instanceText = (AutoCompleteTextView) findViewById(R.id.expense_instance_account);
		final EditText description = (EditText) findViewById(R.id.description);
		final EditText expenseDate = (EditText) findViewById(R.id.expenseDate);
		final EditText amount = (EditText) findViewById(R.id.amount);

		expenseDate.setText(sdf.format(new Date()));

		/*****************************************************************************************************
		 * Setup ExpenseType view
		 *****************************************************************************************************/
		Cursor typeCursor = getContentResolver().query(ExpenseType.CONTENT_URI,
				ExpenseType.PROJECTIONS, null, null, null);
		String[] types = new String[typeCursor.getCount()];
		int i = 0;
		while (typeCursor.moveToNext()) {
			ExpenseType t = new ExpenseType();
			t.setId(typeCursor.getLong(typeCursor
					.getColumnIndex(ExpenseType.ID)));
			t.setCode(typeCursor.getString(typeCursor
					.getColumnIndex(ExpenseType.CODE)));
			t.setExpenseType(typeCursor.getString(typeCursor
					.getColumnIndex(ExpenseType.EXPENSE_TYPE)));
			typesMap.put(t.getExpenseType(), t);
			types[i] = t.getExpenseType();
			i++;
		}

		typeCursor.close();
		ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, types);
		typeText.setAdapter(typeAdapter);

		/*****************************************************************************************************
		 * Setup AccountInstance view
		 *****************************************************************************************************/

		Cursor instanceCursor = getContentResolver().query(
				AccountInstance.CONTENT_URI, AccountInstanceList.PROJECTIONS,
				null, null, null);
		String[] instances = new String[instanceCursor.getCount()];
		// System.out.println("found instances " + instances.length);
		i = 0;
		while (instanceCursor.moveToNext()) {
			AccountInstance ai = new AccountInstance();
			ai.setBudget(instanceCursor.getDouble(instanceCursor
					.getColumnIndex(AccountInstance.BUDGET)));
			ai.setInstance(instanceCursor.getString(instanceCursor
					.getColumnIndex(AccountInstance.INSTANCE)));
			ai.setId(instanceCursor.getLong(instanceCursor
					.getColumnIndex(AccountInstance.ID)));
			ai.setBudget(instanceCursor.getDouble(instanceCursor
					.getColumnIndex(AccountInstance.BUDGET)));
			instances[i] = ai.getInstance();
			instancesMap.put(ai.getInstance(), ai);

			// System.out.println("instance is " + ai.getInstance());
			i++;
		}

		instanceCursor.close();
		ArrayAdapter<String> instanceAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, instances);
		instanceText.setAdapter(instanceAdapter);

		/**
		 * Process input from the list activity
		 */
		Bundle bundle = getIntent().getExtras();

		if (bundle != null && bundle.size() > 0) {

			if (bundle.getLong(Expense.ID) > 0) {
				expense.setId(bundle.getLong(Expense.ID));
			}

			Cursor ec = getContentResolver().query(Expense.CONTENT_URI,
					Expense.PROJECTIONS, Expense.ID + " = " + expense.getId(),
					null, null);
			if (ec.moveToFirst()) {
				// if (bundle.getLong(Expense.EXPENSE_TYPE) > 0) {
				Cursor etc = getContentResolver().query(
						ExpenseType.CONTENT_URI,
						ExpenseType.PROJECTIONS,
						ExpenseType.ID
								+ " = "
								+ ec.getString(ec
										.getColumnIndex(Expense.EXPENSE_TYPE)),
						null, null);

				ExpenseType et = new ExpenseType();
				if (etc.moveToFirst()) {
					et.setId(ec.getLong(ec.getColumnIndex(Expense.EXPENSE_TYPE)));
					et.setCode(etc.getString(etc
							.getColumnIndex(ExpenseType.CODE)));
					et.setExpenseType(etc.getString(etc
							.getColumnIndex(ExpenseType.EXPENSE_TYPE)));
				}
				etc.close();
				expense.setExpenseType(et);
				// }

				// if (bundle.getLong(AccountInstance.ID) > 0) {
				Cursor aic = getContentResolver()
						.query(AccountInstance.CONTENT_URI,
								AccountInstance.PROJECTIONS,
								AccountInstance.ID
										+ " = "
										+ ec.getLong(ec
												.getColumnIndex(Expense.ACCOUNT_INSTANCE)),
								null, null);

				AccountInstance ai = new AccountInstance();
				if (aic.moveToFirst()) {
					ai.setId(ec.getLong(ec
							.getColumnIndex(Expense.ACCOUNT_INSTANCE)));

					ai.setInstance(aic.getString(aic
							.getColumnIndex(AccountInstance.INSTANCE)));
					// ai.setAccount(new
					// Account(aic.getLong(aic.getColumnIndex(AccountInstance.ACCOUNT_FK)),
					// "", ""));
					ai.setBudget(aic.getDouble(aic
							.getColumnIndex(AccountInstance.BUDGET)));
					SimpleDateFormat sdfi = new SimpleDateFormat(
							AccountInstance.DATE_FORMAT);

					try {
						// System.out.println("Date is : " + aic.getString(aic
						// .getColumnIndex(AccountInstance.START_DATE)));
						ai.setStartDate(sdfi.parse(aic.getString(aic
								.getColumnIndex(AccountInstance.START_DATE))));

						if (aic.getString(aic
								.getColumnIndex(AccountInstance.CLOSE_DATE)) != null
								&& aic.getString(
										aic.getColumnIndex(AccountInstance.CLOSE_DATE))
										.length() > 0) {
							ai.setCloseDate(sdfi.parse(aic.getString(aic
									.getColumnIndex(AccountInstance.CLOSE_DATE))));
						}

					} catch (ParseException e) {
						e.printStackTrace();
					}

				}
				aic.close();
				expense.setAccountInstance(ai);
				// }

				// if (bundle.getString(Expense.EXPENSE_DATE).length() > 0) {
				try {
					System.out.println("Expense date is "
							+ ec.getString(ec
									.getColumnIndex(Expense.EXPENSE_DATE)));
					expense.setExpenseDate(sdf.parse(ec.getString(ec
							.getColumnIndex(Expense.EXPENSE_DATE))));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				// }

				// if (bundle.getString(Expense.DESCRIPTION).length() > 0) {
				expense.setDescription(ec.getString(ec
						.getColumnIndex(Expense.DESCRIPTION)));
				// }

				// if (bundle.getDouble(Expense.AMOUNT) > 0) {
				expense.setAmount(ec.getDouble(ec
						.getColumnIndex(Expense.AMOUNT)));
				// }
			}
			ec.close();
		}

		amount.setText("" + expense.getAmount());
		description.setText(expense.getDescription() == null ? "" : expense
				.getDescription());
		expenseDate
				.setText(sdf.format(expense.getExpenseDate() == null ? new Date()
						: expense.getExpenseDate()));
		instanceText.setText(expense.getAccountInstance() == null ? ""
				: expense.getAccountInstance().getInstance());
		typeText.setText(expense.getExpenseType() == null ? "" : expense
				.getExpenseType().getExpenseType());

		Button saveButton = (Button) findViewById(R.id.saveExpenseButton);
		saveButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				expense.setAmount(Double.parseDouble(amount.getText()
						.toString()));

				expense.setDescription(description.getText().toString());
				expense.setAccountInstance(instancesMap.get(instanceText
						.getText().toString()));
				expense.setExpenseType(typesMap.get(typeText.getText()
						.toString()));

				try {
					if (expenseDate.getText().toString().length() == 10) {
						expense.setExpenseDate(sdf.parse(expenseDate.getText()
								.toString()));
					} else {
						expense.setExpenseDate(null);
					}

				} catch (ParseException e) {
					e.printStackTrace();
				}

				ContentResolver cr = getContentResolver();
				ContentValues values = new ContentValues();

				values.put(Expense.AMOUNT, expense.getAmount());
				values.put(Expense.DESCRIPTION, expense.getDescription());

				if (expense.getExpenseDate() != null) {

					values.put(Expense.EXPENSE_DATE,
							sdf.format(expense.getExpenseDate()));
				}

				values.put(Expense.EXPENSE_TYPE, expense.getExpenseType()
						.getId());
				values.put(Expense.ACCOUNT_INSTANCE, expense
						.getAccountInstance().getId());

				if (expense.getId() == null || expense.getId() == 0) {
					cr.insert(Expense.CONTENT_URI, values);

					String s = Expense.DESCRIPTION + " = '"
							+ expense.getDescription() + "' AND "
							+ Expense.ACCOUNT_INSTANCE + " = "
							+ expense.getAccountInstance().getId() + " AND "
							+ Expense.EXPENSE_TYPE + " = "
							+ expense.getExpenseType().getId();
					Cursor c = cr.query(Expense.CONTENT_URI,
							Expense.PROJECTIONS, s, null, null);
					if (c.moveToFirst()) {
						expense.setId(c.getLong(c.getColumnIndex(Expense.ID)));
					}
					c.close();
				} else {
					cr.update(Expense.CONTENT_URI, values,
							"_id = " + expense.getId(), null);
				}

				// showList("", "");
			}
		});

		Button newButton = (Button) findViewById(R.id.newExpenseButton);
		newButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				expense.setExpenseDate(null);
				expense.setExpenseType(null);
				expense.setAccountInstance(null);
				expense.setAmount(0.00);
				expense.setDescription(null);

				amount.setText("0.00");
				description.setText(null);
				typeText.setText(null);
				expenseDate.setText(null);
				instanceText.setText(null);
			}
		});

		Button deleteButton = (Button) findViewById(R.id.deleteExpenseButton);
		deleteButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ContentResolver cr = getContentResolver();
				if (expense.getId() != null || expense.getId() > 0) {
					cr.delete(Expense.CONTENT_URI, "_id = " + expense.getId(),
							null);
				}

				amount.setText("0.00");
				description.setText(null);
				typeText.setText(null);
				expenseDate.setText(null);
				instanceText.setText(null);

				expense.setId(0L);
				try {
					expense.setExpenseDate(sdf.parse(expenseDate.getText()
							.toString()));
				} catch (ParseException e) {
					e.printStackTrace();
				}

				expense.setAccountInstance(instancesMap.get(instanceText
						.getText().toString()));
				expense.setExpenseType(typesMap.get(typeText.getText()
						.toString()));
				expense.setDescription(description.getText().toString());
				expense.setAmount(Double.parseDouble(amount.getText()
						.toString()));

				// showList("", "");
			}
		});

		Button searchButton = (Button) findViewById(R.id.searchExpenseButton);
		searchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				expense.setAmount(Double.parseDouble(amount.getText()
						.toString()));

				expense.setDescription(description.getText().toString());
				expense.setAccountInstance(instancesMap.get(instanceText
						.getText().toString()));
				expense.setExpenseType(typesMap.get(typeText.getText()
						.toString()));

				try {
					if (expenseDate.getText().toString().length() == 10) {
						expense.setExpenseDate(sdf.parse(expenseDate.getText()
								.toString()));
					} else {
						expense.setExpenseDate(null);
					}

				} catch (ParseException e) {
					e.printStackTrace();
				}

				Double amnt = expense.getAmount();
				String desc = expense.getDescription();
				Date sDate = expense.getExpenseDate();
				ExpenseType xtp = expense.getExpenseType();
				AccountInstance acin = expense.getAccountInstance();

				expense.setExpenseDate(null);
				expense.setExpenseType(null);
				expense.setAccountInstance(null);
				expense.setAmount(0);
				expense.setDescription(null);

				amount.setText("0.00");
				description.setText(null);
				typeText.setText(null);
				expenseDate.setText(null);
				instanceText.setText(null);

				showList(desc, acin, sDate, amnt, xtp);
			}
		});

		if (instancesMap.size() == 0 || typesMap.size() == 0) {
			typeText.setEnabled(false);
			instanceText.setEnabled(false);
			typeText.setEnabled(false);
			instanceText.setEnabled(false);
			typeText.setEnabled(false);
		}
	}

	private void showList(String description, AccountInstance instance,
			Date sDate, Double amount, ExpenseType type) {
		Intent intent = new Intent(this, ExpenseList.class);
		if (description != null) {
			intent.putExtra(Expense.DESCRIPTION, description);
		}

		if (sDate != null) {
			intent.putExtra(Expense.EXPENSE_DATE, sDate);
		}

		if (amount != null && amount > 0) {
			intent.putExtra(Expense.AMOUNT, amount);
		}

		if (instance != null) {
			intent.putExtra(Expense.ACCOUNT_INSTANCE, instance);
		}

		if (type != null) {
			intent.putExtra(Expense.EXPENSE_TYPE, type);
		}

		startActivityForResult(intent, 1);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.manage_expense, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent = IntentHandler.handleOnOptionsItemSelected(this,
				item.getItemId());
		startActivityForResult(intent, 1);
		return super.onOptionsItemSelected(item);
	}
}
